package com.gome.datasource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.gome.bg.entity.User;
import com.gome.util.TraceInfo;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

public class MongoTemplate {

	@Autowired
	private MongoDBDataSource mongoDataSource;

	/**
	 * 增加
	 * 
	 * @param obj
	 */
	public void add(DBObject obj) {
		DBCollection coll = mongoDataSource.initDBCollection();
		coll.insert(obj);
	}

	/**
	 * 删除
	 * 
	 * @param obj
	 */
	public void delete(DBObject obj) {
		DBCollection coll = mongoDataSource.initDBCollection();
		coll.remove(obj);
	}

	/**
	 * 查询
	 */
	public Object query() {
		DBCollection coll = mongoDataSource.initDBCollection();
		DBCursor cur = coll.find();
		List list = new ArrayList();
		while (cur.hasNext()) {
			Map map= new HashMap();
			DBObject object = cur.next();
			TraceInfo.trace(getClass()).info(object.toString());
			map = object.toMap();
			list.add(map);
			//TraceInfo.trace(getClass()).info("uname:" + object.get("uname") + "\tupwd:" + object.get("upwd") + "\t_id:" + object.get("_id"));
		}
		return list;
	}

	/**
	 * 修改
	 */
	public void modify(DBObject orig, DBObject update) {
		DBCollection coll = mongoDataSource.initDBCollection();
		coll.update(orig, update, true, false);
	}
	
	

	public MongoDBDataSource getMongoDataSource() {
		return mongoDataSource;
	}

	public void setMongoDataSource(MongoDBDataSource mongoDataSource) {
		this.mongoDataSource = mongoDataSource;
	}

}
